package com.scorpio.basic.service.impl;

import com.scorpio.basic.domain.OssDatumEntity;
import com.scorpio.basic.dto.OssDatumDTO;
import com.scorpio.basic.mapper.OssDatumMapper;
import com.scorpio.basic.service.OssDatumService;
import com.scorpio.basic.vo.OssDatumVo;
import com.scorpio.common.exception.CustomException;
import com.scorpio.common.service.impl.BaseServiceImpl;
import com.scorpio.common.utils.ConvertUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OssDatumServiceImpl extends BaseServiceImpl<OssDatumMapper, OssDatumEntity> implements OssDatumService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OssDatumEntity save(String tableName, Long tableId, String resources) {
        return save(tableName, tableId, resources, 0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OssDatumEntity save(String tableName, Long tableId, String resources, Integer sort) {
        OssDatumEntity entity = new OssDatumEntity();
        entity.setTableName(tableName);
        entity.setTableId(tableId);
        entity.setResources(resources);
        entity.setSort(sort);
        int count = baseDao.insert(entity);
        if (count == 0) {
            throw new CustomException("操作失败");
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(OssDatumEntity entity) {
        return baseDao.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSort(Long id, Integer sort) {
        return baseDao.updateSort(id, sort);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void imports(String tableName, Long tableId, String... resources) {
        if (resources == null) {
            return;
        }
        for (String r : resources) {
            OssDatumEntity entity = new OssDatumEntity();
            entity.setTableName(tableName);
            entity.setTableId(tableId);
            entity.setResources(r);
            baseDao.insert(entity);
        }
    }

    @Override
    public String[] selectImages(String tableName, Long tableId) {
        return baseDao.selectImages(tableName, tableId);
    }

    @Override
    public List<OssDatumDTO> selectList(String tableName, Long tableId) {
        return ConvertUtils.sourceToTarget(baseDao.selectByTableList(tableName, tableId), OssDatumDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDelete(Long id) {
        return baseDao.updateDelete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDeleteNotContain(String tableName, Long tableId, List<Long> ids) {
        return baseDao.updateDeleteNotContain(tableName, tableId, ids);
    }

}
